﻿using Abp.Authorization;
using Paas.App.Interface.Common;
using Paas.App.Interface.Common.Messages;
using Paas.App.Interface.Documents;
using Paas.App.Interface.Documents.Messages;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Basefr.Consts;
using Basefr.Web.Controllers;

namespace Paas.Svc.Host.Controllers
{
    [Route("Download")]
    [EnableCors("Paas")]
    [AbpAllowAnonymous]
    public class DownloadController : WebController
    {
        private readonly IFileAppService _fileAppService;
        private readonly IDocumentAppService _documentAppService;

        public DownloadController(IFileAppService fileAppService, IDocumentAppService documentAppService)
        {
            _fileAppService = fileAppService;
            _documentAppService = documentAppService;
        }

        [HttpGet(nameof(File))]
        public IActionResult File(int id, string code)
        {
            var output = _fileAppService.DownloadFile(new DownloadFileInput { Id = id, Code = code });

            if (string.IsNullOrWhiteSpace(code) || !output.Item.Code.ToUpper().StartsWith(code.ToUpper()))
            {
                return Content("校验码错误，禁止下载文件");
            }

            return File(output.FileStream, output.Item.MimeType ?? "application/octet-stream", output.Item.Name);
        }

        [HttpGet(nameof(Document))]
        public IActionResult Document(int id, string code)
        {
            var output = _documentAppService.DownloadDocument(new DownloadDocumentInput { Id = id, Code = code });

            if (string.IsNullOrWhiteSpace(code) || !output.Item.Code.ToUpper().StartsWith(code.ToUpper()))
            {
                return Content("校验码错误，禁止下载文件");
            }

            return File(output.DocumentStream, ContentType.Stream, output.Item.Name);
        }
    }
}
